package com.zhong.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.sun.jdi.InternalException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class HelloController {

    private static final String RESOURCE_NAME = "hello";
    private static final String USER_RESOURCE_NAME = "user";
    private static final String DEGRADE_RESOURCE_NAME = "degrade";


    @RequestMapping("/hello")
    public String hello(){
        Entry entry = null;
        try {
            // sentinel 针对资源限制
            SphU.entry(RESOURCE_NAME);
            // 被保护的业务逻辑
            String str = "hello sentinel";
            log.info("==========="+str+"===========");
            return str;
        } catch (BlockException e) {
            // 资源阻止访问， 被限流和降级
            // 进行相应处理
            log.info("block");
            return "被流控了";
        } catch (Exception e){
            Tracer.traceEntry(e, entry);
        }finally {
            if (entry != null){
                entry.exit();
            }
        }
        return null;
    }

    @PostConstruct
    private static void initFlowRules(){
        ArrayList<FlowRule> rules = new ArrayList<>();
        // 流控规则
        FlowRule rule = new FlowRule();
        // 设置被 保护的资源
        rule.setResource(RESOURCE_NAME);
        // 设置流控规则的模式
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置保护的阈值
        rule.setCount(1);
        rules.add(rule);



        // 流控规则
        FlowRule rule2 = new FlowRule();
        // 设置被 保护的资源
        rule2.setResource(USER_RESOURCE_NAME);
        // 设置流控规则的模式
        rule2.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置保护的阈值
        rule2.setCount(1);
        rules.add(rule2);

        // 加载配置号的规则
        FlowRuleManager.loadRules(rules);

    }


    @PostConstruct
    private static void initDegradeRules(){
        List<DegradeRule> degradeRules = new ArrayList<>();
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource(DEGRADE_RESOURCE_NAME);
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT);
        degradeRule.setCount(2);
        degradeRule.setTimeWindow(10);
        degradeRule.setMinRequestAmount(2);

        degradeRule.setStatIntervalMs(60*60*1000);

        degradeRules.add(degradeRule);
        DegradeRuleManager.loadRules(degradeRules);





    }

    @RequestMapping("/degrade")
    @SentinelResource(value = DEGRADE_RESOURCE_NAME, entryType = EntryType.IN,
            blockHandler = "blockHandlerForFb"
    )
    public String degrade(String id) throws InterruptedException {
        throw new RuntimeException("异常");
    }

    public String blockHandlerForFb(String id, BlockException e){
        return "降级了";
    }

    /**
     * 1、依赖
     * 2、配置bean SentinelResourceAspect
     * value: 定义资源
     * blockHandler： 降级 的处理   默认 方法是再同一个类中
     *  一定要public 返回值要一致，参数一致，
     *
     *  blockHandlerClass可以不用在同一个类中
     *
     *
     */

    @RequestMapping("/user")
    @SentinelResource(value = USER_RESOURCE_NAME, blockHandler = "blockHandlerForUser")
    public String getUser(String id){
        return "获取user资源";

    }

    public String blockHandlerForUser(String id, BlockException e){
        e.printStackTrace();
        return "被限流了";
    }


}
